package com.tegistuff.webos.run.debugger.commands;

import com.tegistuff.webos.run.debugger.infrastructure.WebOSDebuggerConstants;
import org.json.JSONException;
import org.json.JSONObject;

/**
 * WebOSEvaluateCommand.java
 *
 * Copyright (C) 2012 Timo Tegtmeier.
 * All rights reserved.
 */
public class WebOSEvaluateCommand extends WebOSDebuggerCommand {

    private String myExpression;
    private int myFrameNumber;
    private JSONObject myResult;

    public WebOSEvaluateCommand(String expression, int frameNumber) {
        myExpression = expression;
        myFrameNumber = frameNumber;
    }
    
    @Override
    public void execute() throws Exception {
        JSONObject args = new JSONObject();
        args.put("frame", myFrameNumber);
        args.put("expression", myExpression);
        args.put("disable_break", true);
        JSONObject request = new JSONObject();
        request.put("command", "evaluate");
        request.put("arguments", args);
        runRequest(request);
    }    
    
    @Override
    protected void onSuccess() throws JSONException {
        if(ourResponse.optBoolean("success", true)) {
            ourDebugProcess.getVariableRepository().append(ourResponse.getJSONArray(WebOSDebuggerConstants.V8_REFERENCES));
            myResult = ourResponse.getJSONObject(WebOSDebuggerConstants.V8_BODY);
        }
    }

    @Override
    protected boolean ignoreSuccessState() {
        return true;
    }

    public JSONObject getResult() {
        return myResult;
    }
}
